<template>
  <div class="upload-image">
    <el-upload
      ref="uploadRef"
      action="#"
      :limit="1"
      :file-list="fileList"
      :disabled="fileList.length >= 1"
      :auto-upload="false"
      list-type="picture-card"
      :on-change="onChange"
    >
      <div class="content">
        <el-icon>
          <Plus />
        </el-icon>
        <div>更新图片</div>
      </div>
    </el-upload>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadUserFile } from 'element-plus'
import { ElNotification } from 'element-plus'
import pageCommon from '@/store/module/page-common'

interface IState {
  pageName?: string
}

const props = withDefaults(defineProps<IState>(), {
  pageName: 'user'
})
//图片上传组件ref属性
const uploadRef = ref()
const fileList = ref<UploadUserFile[]>([])

const onChange = (item: any) => {
  //定义可以上传的图片类型
  const typeArr = ['image/png', 'image/gif', 'image/jpeg', 'image/jpg']
  const isImg = typeArr.indexOf(item.raw.type) !== -1
  const isMore3M = item.raw.size / 1024 / 1024 < 3
  if (!isImg) {
    ElNotification.info('只能上传图片类型!')
    uploadRef.value?.clearFiles()
    return
  }
  if (!isMore3M) {
    ElNotification.info('图片大小超过3M!')
    uploadRef.value?.clearFiles()
    return
  }

  //设置图片上传的参数
  const formData = new FormData()
  formData.append('file', item.raw)
  pageCommon()
    .uploadImageAction(props.pageName, formData)
    .then(() => {
      uploadRef.value?.clearFiles()
    })
}
</script>

<style scoped lang="less">
.upload-image {
  display: flex;
  justify-content: center;
}

.content {
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
